<template>
  <div class="edit-lessson">
    <el-card
      v-loading="startingTranscode"
      element-loading-text="转码中..."
      element-loading-spinner="el-icon-loading"
    >
      <div slot="header">上传课时内容</div>
      <div>
        <el-form :model="form" ref="form" label-width="120px" class="demo-form">
          <el-form-item label="课程名称" required>
            <el-input disabled v-model="courseName"></el-input>
          </el-form-item>
          <el-form-item label="课时名称" required>
            <el-input disabled v-model="theme"></el-input>
          </el-form-item>
          <el-form-item label="视频上传">
            <input ref="lessonVideo" type="file" />
          </el-form-item>
          <el-form-item label="封面上传">
            <input ref="lessonImg" type="file" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleUpload">开始上传</el-button>
            <el-button @click="$router.back()">返回</el-button>
          </el-form-item>
          <el-form-item>
            <div v-if="uploadPercent !== 0">{{ uploadPercent }}%</div>
            <div v-if="isUploadDone">
              {{ isTranscodeDone ? '转码完成' : '转码中...' }}
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
/* eslint-disable */
import {
  aliyunTransCodePercent,
  aliyunTransCode,
  aliyunVideoUploadAddressAdnAuth,
  aliyunImagUploadAddressAdnAuth
} from '@/service/upload-video'
export default {
  props: {
    courseName: {
      type: String
    },
    theme: {
      type: String
    },
    id: {
      type: [Number, String]
    }
  },
  data () {
    return {
      form: {
        courseName: '',
        theme: ''
      },
      // 图片上传后的地址，用于视频上传凭证请求
      imageURL: '',
      // 上传实例
      uploader: null,
      // 上传视频的 ID
      videoId: null,
      // 上传百分比
      uploadPercent: 0,
      // 上传完毕状态
      isUploadDone: false,
      // 转码完毕状态
      isTranscodeDone: false,
      startingTranscode: false
    }
  },
  created () {
    this.initUploader()
  },
  methods: {
    async submitForm (formName) {
      const valid = await this.$refs[formName].validate()
      if (valid) {
        alert('submit!')
      } else {
        console.log('error submit!!')
        return false
      }
    },
    handleUpload () {
      // 考虑到可能重复使用某个组件进行上传处理，点击上传时，将数据重置
      this.uploadPercent = 0
      this.isUploadDone = false
      this.isTranscodeDone = false
      const videoFile = this.$refs['lessonVideo'].files[0]
      const imageFile = this.$refs['lessonImg'].files[0]
      const uploader = this.uploader
      // 将要上传的文件添加到上传列表中
      uploader.addFile(imageFile)
      uploader.addFile(videoFile)
      // 开始上传
      uploader.startUpload()
    },
    initUploader () {
      this.uploader = new window.AliyunUpload.Vod({
        // 阿里账号ID，必须有值
        userId: '1618139964448548',
        // 上传到视频点播的地域，默认值为'cn-shanghai'，//eu-central-1，ap-southeast-1
        region: '',
        // 分片大小默认1 MB，不能小于100 KB
        partSize: 1048576,
        // 并行上传分片个数，默认5
        parallel: 5,
        // 网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        // 网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        // 开始上传
        onUploadstarted: async uploadInfo => {
          let uploadAddressAndAuth = null
          // 检测是图片或视频
          if (uploadInfo.isImage) {
            // 图片处理
            const { data } = await aliyunImagUploadAddressAdnAuth()
            if (data.code === '000000') {
              uploadAddressAndAuth = data.data
              this.imageURL = uploadAddressAndAuth.imageURL
            }
          } else {
            // 视频处理
            const { data } = await aliyunVideoUploadAddressAdnAuth({
              fileName: uploadInfo.file.name,
              imageUrl: this.imageURL
            })
            if (data.code === '000000') {
              uploadAddressAndAuth = data.data
              this.videoId = data.data.videoId
            }
          }
          // 设置凭证与地址
          this.uploader.setUploadAuthAndAddress(
            uploadInfo,
            uploadAddressAndAuth.uploadAuth,
            uploadAddressAndAuth.uploadAddress,
            uploadAddressAndAuth.imageId || uploadAddressAndAuth.videoId
          )
          // 此步设置完毕，上传进度开始执行
        },
        // 文件上传成功
        onUploadSucceed: function (uploadInfo) {},
        // 文件上传失败
        onUploadFailed: function (uploadInfo, code, message) {},
        // 文件上传进度，单位：字节
        onUploadProgress: (uploadInfo, totalSize, loadedPercent) => {
          if (!uploadInfo.isImage) {
            this.uploadPercent = Math.floor(loadedPercent * 100)
          }
        },
        // 上传凭证超时
        onUploadTokenExpired: async uploadInfo => {},
        // 全部文件上传结束
        onUploadEnd: async uploadInfo => {
          this.isUploadDone = true
          //   const lessonId = this.$route.query.lessonId
          // 发送视频转码请求
          this.startingTranscode = true
          const { data } = await aliyunTransCode({
            lessonId: this.id,
            coverImageUrl: this.imageURL,
            fileId: this.videoId,
            fileName: this.$refs['lessonVideo'].files[0].name
          })
          if (data.code === '000000') {
            // 轮询转码进度
            const timer = setInterval(async () => {
              const { data } = await aliyunTransCodePercent({
                lessonId: this.id
              })
              if (data.code === '000000') {
                if (data.data === 100) {
                  this.isTranscodeDone = true
                  this.startingTranscode = false
                  this.$message.success('视频转码成功')
                  clearInterval(timer)
                }
              }
            }, 1000)
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-card__header {
  text-align: left;
}
::v-deep .el-form-item__content {
  text-align: left;
}
</style>
